import * as types from './mutation-types'
import * as publicjs from './public'
// import Vue from 'vue'
import axios from 'axios'
// eslint-disable-next-line
import * as qiniu from 'qiniu-js'
const action = {
  // 更新数据里面好友的信息
    async setFriendsA({commit}, data) {
      await axios.post('/api/users/friends', data)
      .then(res => {
          console.log(res, '数据库设置好友信息调用成功')
          // return Promise.resolve(res.data)
      })
      .catch(err => {
          console.log(err, '数据库设置好友信息调用失败')
      })
        // }
    },
    // 获取users里面的消息列表
    async getDbMessageListA({dispatch, commit, state}, data) {
        console.log(data)
        let result = await axios.get('/api/users/getmessagelist', {params: data})
            .then(res => {
                // console.log(res.data)
                console.log(res.data[0].username, '当前登录的用户')
                return Promise.resolve(res.data)
            })
            .catch(err => {
                console.log(err, '数据库请求历史聊天记录信息调用失败')
                return err
            })
        console.log(result, '数据返回当前登录用户的所有信息')
        if (result.length > 0) {
          // 顺便更新当前登录用户的基本信息
            commit(types.SET_CURRENT_LOGIN_USER, result[0].userInfo)
            // 获取数据库中的聊天信息
            commit(types.GET_DB_MESSAGE_LIST, result[0].messageList)
            // 如果收到添加好友请求的数组不为空
            if (result[0].addNewFriends.length) {
              // 一开始没有这个的时候，就还是没有修改的
              // console.log('难得一见', result[0].addNewFriends)
              commit(types.INIT_REVCIEVE_FRIENDS_POST, result[0].addNewFriends)
            }
            // 顺便更新当前用户的群组列表
            let groupParams = {flag: 1, arr: result[0].groupInfo}
            commit(types.SET_GROUP_INFO, groupParams)
            // console.log(state.groupInfo, '11111')

            // if (result[0].groupMessageList) {
              // 顺便更新当前的群组聊天列表
              let groupMessageList = result[0].groupMessageList || []
              commit(types.SET_GROUP_MESSAGELIST, groupMessageList)
              console.log(groupMessageList, 'groupMessageList')
            // }

            // 顺便更新当前用户的好友列表
            let friends = result[0].friends
            // eslint-disable-next-line
            let length = friends.length
            friends.forEach(f => {
              // 如果没有headicon这个属性，就从数据库里面查一下
              if (!f['headicon']) {
                let obj = {username: f['name']}
                dispatch('getUserInfo', obj).then((res) => {
                  // console.log(res, 'pppppppppp')
                  if (res[0].userInfo.headicon) {
                    f['headicon'] = res[0].userInfo.headicon
                    // console.log(f, 'wwwwwwwwwwww')
                  }
                  length--
                  // console.log(length, 'qqqqqqqqq')
                  if (length <= 0) {
                    let data = {flag: '1', friends: friends}
                    console.log(friends, 'eeeeeeeeeeee')
                    commit(types.SET_CURRENTUSER_FRIENDSLIST, data)
                    let params = {friends: friends, username: state.currentLoginUser.username}
                    dispatch('setFriendsA', params)
                  }
                }).catch(err => {
                  length--
                  if (length <= 0) {
                    let data = {flag: '1', friends: friends}
                    console.log(friends, 'eeeeeeeeeeee')
                    commit(types.SET_CURRENTUSER_FRIENDSLIST, data)
                    let params = {friends: friends, username: state.currentLoginUser.username}
                    dispatch('setFriendsA', params)
                  }
                  console.log(err, '获取用户信息失败')
                })
              } else {
                length--
                if (length <= 0) {
                  let data = {flag: '1', friends: friends}
                  console.log(friends, 'eeeeeeeeeeee')
                  commit(types.SET_CURRENTUSER_FRIENDSLIST, data)
                  let params = {friends: friends, username: state.currentLoginUser.username}
                  dispatch('setFriendsA', params)
                }
              }
            })
            console.log(state.messageList1)
        }
    },
    // 获取用户信息
    async getUserInfo({dispatch, commit}, obj) {
      let result = await axios.get('/api/users/getmessagelist', {params: obj})
              .then(res => {
                  return Promise.resolve(res.data)
              })
              .catch(err => {
                  console.log(err, '好友失败')
                  return err
              })
      return result
    },
    // 收到消息之后设置users里面的消息列表
    async setDbMessageListA({commit, state}, message) {
        // message每次刚刚登陆时候收到的消息，每一次都存进数据库
        console.log(Object.getOwnPropertyNames(message).length, '检测收到的消息是否为空')
        let index = state.messageList1.length || 0
        let result = publicjs.cloneObj(state.messageList1)
        // 每一次在这里构建列表 当列表不为空，并且收到的消息也不是空的时候
        if (result.length > 0 && Object.getOwnPropertyNames(message).length !== 0) {
           let tempitem = result.filter((item, i) => {
             if (item['name'] === message['from']) {
               index = i
               return item
             }
           })
          // console.log(tempitem, index)
          if (tempitem.length <= 0) {
            // console.log(1111111112)
            // 如果该消息列表还没有与该好友的聊天记录，字节将本次消息写入消息列表
            let obj = {}
            obj['_id'] = '1105181206098244#mini-chat_' + message['from'] + '@easemob.com'
            obj['name'] = message['from']
            obj['list'] = []
            let time
            if (message.delay) {
              time = new Date(message.delay).getTime()
            } else {
              time = new Date().getTime()
            }
            obj['list'].push({msg: message['data'], time: time, read: false, self: false})
            commit(types.INIT_GETUNREAD_MESSAGE_LIST, {index: index, obj: obj})
            result.push(obj)
            // console.log(result, '77777777777')
          } else {
            let time
            if (message.delay) {
              time = new Date(message.delay).getTime()
            } else {
              time = new Date().getTime()
            }
            // console.log(time, '收到消息的时间')
            tempitem[0].list.push({msg: message['data'], time: time, read: false, self: false})
            commit(types.INIT_GETUNREAD_MESSAGE_LIST, {index: index, obj: tempitem[0]})
          }
          // console.log(tempitem)
        } else if (Object.getOwnPropertyNames(message).length !== 0) {
          let obj = {}
          obj['_id'] = '1105181206098244#mini-chat_' + message['from'] + '@easemob.com'
          obj['name'] = message['from']
          console.log(obj)
          obj['list'] = []
          let time
          if (message.delay) {
            time = new Date(message.delay).getTime()
          } else {
            time = new Date().getTime()
          }
          // console.log(time, '收到消息的时间')
          obj['list'].push({msg: message['data'], time: time, read: false, self: false})
          commit(types.INIT_GETUNREAD_MESSAGE_LIST, {index: index, obj: obj})
          result.push(obj)
        }
        // console.log('收到消息后的列表', result)
        let data = {messageList: result, username: state.currentLoginUser.username}
        // console.log(data, result)
        await axios.post('/api/users/setMessageList', data)
            .then(res => {
                console.log(res)
                // return Promise.resolve(res.data)
            })
            .catch(err => {
                console.log(err, '数据库请求历史聊天记录信息调用失败')
            })
        // } commit(types.GET_DB_MESSAGE_LIST, data)
    },
    // 发送消息之后设置users里面的消息列表
    async setDbMessageListAS({commit, state}, message) {
      console.log(state.messageList1, message)
      let tempitem = state.messageList1.filter(item => {
        // 这里的判断需要修改
        // console.log(item._id, data.id)
      if (item._id === message.id) {
          return item
        }
      })
      // console.log(tempitem)
      // 原先没有聊天过的，添加聊天用户进聊天列表
      if (tempitem.length === 0) {
        let tempcurrent = {}
        tempcurrent['_id'] = message.id
        tempcurrent['name'] = message.name
        tempcurrent['list'] = []
        tempcurrent['list'].push({...message.msg})
        // console.log(tempcurrent, '222222222')
        state.messageList1.push({...tempcurrent})
      } else {
        // console.log(tempitem[0].list, data.msg)
        // 原先有聊天过的，直接添加聊天消息
        tempitem[0].list.push(message.msg)
        // console.log(tempitem, '11111111111111')
      }
      // state.messageList1.splice(4, 1)
      console.log(state.messageList1, '33333333333')
      let data = {messageList: state.messageList1, username: state.currentLoginUser.username}
      console.log(data)
      await axios.post('/api/users/setMessageList', data)
          .then(res => {
              console.log(res)
              // return Promise.resolve(res.data)
          })
          .catch(err => {
              console.log(err, '数据库请求历史聊天记录信息调用失败')
          })
/*
      // message每次发送的消息，每一次都存进数据库 id name msg
      console.log(Object.getOwnPropertyNames(message).length, '检测发送的消息是否为空')
      let index = state.messageList1.length || 0
      let result = publicjs.cloneObj(state.messageList1)
      // 每一次在这里构建列表 当列表不为空，并且发送的消息也不是空的时候
      if (result.length > 0 && Object.getOwnPropertyNames(message).length !== 0) {
         let tempitem = result.filter((item, i) => {
           if (item['name'] === message['from']) {
             index = i
             return item
           }
         })
        console.log(tempitem, index)
        if (tempitem.length <= 0) {
          // console.log(1111111112)
          // 如果该消息列表还没有与该好友的聊天记录，字节将本次消息写入消息列表
          let obj = {}
          obj['_id'] = '1105181206098244#mini-chat_' + message['from'] + '@easemob.com'
          obj['name'] = message['from']
          obj['list'] = []
          let time
          if (message.delay) {
            time = new Date(message.delay).getTime()
          } else {
            time = new Date().getTime()
          }
          obj['list'].push({msg: message['data'], time: time, read: false, self: false})
          commit(types.INIT_GETUNREAD_MESSAGE_LIST, {index: index, obj: obj})
          result.push(obj)
          console.log(result, '77777777777')
        } else {
          let time
          if (message.delay) {
            time = new Date(message.delay).getTime()
          } else {
            time = new Date().getTime()
          }
          console.log(time, '收到消息的时间')
          tempitem[0].list.push({msg: message['data'], time: time, read: false, self: false})
          commit(types.INIT_GETUNREAD_MESSAGE_LIST, {index: index, obj: tempitem[0]})
        }
        // console.log(tempitem)
      } else if (Object.getOwnPropertyNames(message).length !== 0) {
        let obj = {}
        obj['_id'] = '1105181206098244#mini-chat_' + message['from'] + '@easemob.com'
        obj['name'] = message['from']
        console.log(obj)
        obj['list'] = []
        let time
        if (message.delay) {
          time = new Date(message.delay).getTime()
        } else {
          time = new Date().getTime()
        }
        console.log(time, '收到消息的时间')
        obj['list'].push({msg: message['data'], time: time, read: false, self: false})
        commit(types.INIT_GETUNREAD_MESSAGE_LIST, {index: index, obj: obj})
        result.push(obj)
      }
      console.log('发送消息后的列表', result)
      let data = {messageList: result, username: state.currentLoginUser.username}
      console.log(data, result)
      await axios.post('/api/users/setMessageList', data)
          .then(res => {
              console.log(res)
              // return Promise.resolve(res.data)
          })
          .catch(err => {
              console.log(err, '数据库请求历史聊天记录信息调用失败')
          })
      // } commit(types.GET_DB_MESSAGE_LIST, data)
    */
    },
    // 删除聊天列表的某一项
    async deleteDbMessageList({commit, state}, jid) {
      // 删除vuex聊天列表
      commit(types.DELETE_MESSAGE_LIST, jid)
      /*
      let arr = publicjs.cloneObj(state.messageList1)
      let index = arr.findIndex(f => f['_id'] === jid)
      arr.splice(index, 1)
      // console.log(arr, '88888888888888888888888888888888')
      let data = {username: state.currentLoginUser.username, messageList: arr}
      await axios.post('/api/users/setMessageList', data)
          .then(res => {
              console.log(res, '数据库删除好友聊天列表某一项成功')
          })
          .catch(err => {
              console.log(err, '数据库删除好友聊天列表某一项失败')
      })
      */
      let data = {username: state.currentLoginUser.username, jid: jid}
        await axios.post('/api/users/deleteMessageList', data)
            .then(res => {
                console.log(res, '数据库删除好友聊天列表某一项成功')
            })
            .catch(err => {
                console.log(err, '数据库删除好友聊天列表某一项失败')
        })
    },
  // 接收到好友的信息时，将内容存进添加好友的数据库
    async setAddFriendsPost({commit, state}, message) {
      if (message.from !== 'undefined') {
        // read读取 agree同意与否
        let obj = {read: false, agree: false}
        Object.assign(message, obj)
        console.log(message, '后期判断一下是不是好友，如果是的话，就不要执行下面的东西，也可以在添加好友的时候就判断是不是已经是好友，如果是的话，就不给添加')
        // 判断一下是不曾经发过一次请求了，如果有，就把原先的好友请求的read由false改true，并放到最前面，再添加
        // state.onPresenceFriends.push(message)
        // 如果数据库已经有，再次收到请求，将不再添加项
        // let arr = publicjs.cloneObj(state.onPresenceFriends)
        let tempitem = state.onPresenceFriends.find(f => f.from === message.from) || {}
        // console.log(tempitem, 'pppppppppppppppppppppppp')
        // resetFlag:true 修改本项的agree  false不修改mutation直接push
        // console.log(tempitem, Object.getOwnPropertyNames(tempitem).length, '77777777777777777777777777777777777777777777')
        if (!Object.getOwnPropertyNames(tempitem).length) {
          // arr.push(message)
          // console.log(arr, '78978978977978978978978797878787897897878778')
          let obj = {message: message, resetFlag: false}
          commit(types.REVCIEVE_FRIENDS_POST, obj)
        } else {
          // tempitem['read'] = true
          // tempitem['agree'] = false
          // console.log(arr, '78978978977978978978978797878787897897878778')
          let obj = {message: message, resetFlag: true}
          commit(types.REVCIEVE_FRIENDS_POST, obj)
        }
        // console.log(state.onPresenceFriends)
        // console.log('当前登录的用户', state.currentLoginUser.username)
        let data = {username: state.currentLoginUser.username, message: message}
        // let data = {username: 'cwf40', message: message}
        console.log(data, '000000000000000000000000000000000000000')
        await axios.post('/api/users/setaddNewFriend', data)
            .then(res => {
                console.log(res, '数据库存储好友添加信息成功')
                // return Promise.resolve(res.data)
            })
            .catch(err => {
                console.log(err, '数据库存储好友添加信息失败')
            })
        }
    },
    // 接受或者拒绝好友之后，修改数据库中的read和agree
    async resetAddFriendsPost({commit, state}, obj) {
      // let arr = publicjs.cloneObj(state.onPresenceFriends)
      // let tempitem = arr.find(f => f.fromJid === obj.jid) || {}
      // if (Object.getOwnPropertyNames(tempitem).length) {
      //   tempitem['read'] = obj.read
      //   tempitem['agree'] = obj.agree
      // }
        // 接受好友之后，修改vuex中的read和agree
      commit(types.RESET_REVCIEVE_FRIENDS_POST, obj)
      // console.log(obj, '88888888888888888888888888888888')
      let data = {username: state.currentLoginUser.username, obj: obj}
      await axios.post('/api/users/resetaddNewFriend', data)
          .then(res => {
              console.log(res, '数据库修改好友添加信息成功')
          })
          .catch(err => {
              console.log(err, '数据库修改好友添加信息失败')
      })
    },
    // 添加好友，将更新好友列表之后，将数据库的好友列表进行更新
    async resetCurrentuserFriendlist({commit, state}, friendObj) {
      let obj = {username: friendObj['name']}
      let result = await axios.get('/api/users/getmessagelist', {params: obj})
        .then(res => {
            // console.log(res.data)
            console.log(res.data[0].username, '当前添加的好友')
            return Promise.resolve(res.data)
        })
        .catch(err => {
            console.log(err, '数据库请求当前添加的好友失败')
            return err
        })
      if (result[0].userInfo.headicon) {
        friendObj['headicon'] = result[0].userInfo.headicon
      }
      // console.log(result)
     commit(types.ADD_CURRENTUSER_FRIENDSLIST, friendObj)
     let data = {username: state.currentLoginUser.username, friendObj: friendObj}
      // arr.splice(index, 1) 修改数据库好友列表
      await axios.post('/api/users/friendsAdd', data)
      .then(res => {
          console.log(res, '数据库添加好友列表信息成功')
          // return Promise.resolve(res.data)
      })
      .catch(err => {
          console.log(err, '数据库添加好友列表信息失败')
      })
    },
    // 删除添加好友列表记录
    async deleteAddNewFriends({commit, state}, jid) {
      // 删除vuex添加好友列表
      commit(types.DELETE_REVCIEVE_FRIENDS_POST, jid)
      let data = {username: state.currentLoginUser.username, jid: jid}
      await axios.post('/api/users/deleteaddNewFriend', data)
      .then(res => {
          console.log(res, '数据库删除好友添加信息成功')
      })
      .catch(err => {
          console.log(err, '数据库删除好友添加信息失败')
      })
    },
    // 删除好友 jid长长的ID
    async deleteFriendList({commit, state}, jid) {
      // 删除vuex好友列表
      commit(types.DELETE_CURRENTUSER_FRIENDSLIST, jid)
      // 删除vuex聊天列表
      commit(types.DELETE_MESSAGE_LIST, jid)
      let data = {username: state.currentLoginUser.username, jid: jid}
      // 删除数据库好友列表和数据库聊天列表
      await axios.post('/api/users/friendsDelete', data)
          .then(res => {
              console.log(res, '数据库删除好友信息成功')
          })
          .catch(err => {
              console.log(err, '数据库删除好友信息失败')
      })
    },
    // 用户登录就获取到群组的相关信息 包括群成员 群主************
    async getGroupInfo({commit, dispatch, state}, option) {
      // console.log(state.groupInfo, '22222', option)
      // state.groupInfo从数据库中获取到的数据
      // option 环信上面获取到的数据
      let result = state.groupInfo.filter(f => f.id === option.id)
      if (!result.length) {
        // 将具体的群组信息存入vuex
        let groupParams = {flag: 2, arr: [option]}
        commit(types.SET_GROUP_INFO, groupParams)
        // 将具体的群组信息存入数据库
        let data = {username: state.currentLoginUser.username, groupOption: option}
        // console.log(data)
        dispatch('addGroupOption', data)
      }
    },
    // 收到群组邀请后的添加一个群组的信息**************
    async addGroupInfo({commit, dispatch, state}, option) {
      commit(types.ADD_GROUP_INFO, option)
      // console.log('收到群组邀请后的添加一个群组的信息', option)
      // 将信息存进数据库*************
      let data = {username: state.currentLoginUser.username, groupOption: option}
      dispatch('addGroupOption', data)
      // 从数据库里面获取群成员的头像信息
      /*
      let length = option.affiliations_count
      option.affiliations.forEach(item => {
        // 这里先判断一下数据库里面的数据是否已经有headicon这个属性了
        let obj = { username: item.member || item.owner }
        dispatch('getUserInfo', obj).then((res) => {
          if (res[0].userInfo.headicon) {
            item['headicon'] = res[0].userInfo.headicon
            console.log(item, 'wwwwwwwwwwww')
          } else {
            item['headicon'] = ''
          }
        }).catch(err => {
          console.log(err, '从数据库里面获取群成员的头像信息err')
        })
        length--
        if (length <= 0) {
          let data = {username: state.currentLoginUser.username, groupOption: option}
          console.log(data, '1233333333333')
          dispatch('addGroupOption', data)
        }
      })
      */
    },
    // 添加群信息子函数
    async addGroupOption({commit}, data) {
      await axios.post('/api/users/setGroupOption', data)
      .then(res => {
          console.log(res, '数据库添加群信息成功')
          // return Promise.resolve(res.data)
      })
      .catch(err => {
          console.log(err, '数据库添加群信息成功')
      })
    },
    async getGroupInfoSingle({commit, dispatch, state}, option) {
      // console.log(state.groupInfo, '22222')
      // let result = state.groupInfo.filter(f => f.id === option.id)
      // if (!result.length) {
        // 将具体的群组信息存入vuex
        // let groupParams = {flag: 2, arr: [option]}
        // commit(types.SET_GROUP_INFO, groupParams)
        // 将具体的群组信息存入数据库
        let data = {username: state.currentLoginUser.username, groupOption: option}
        // console.log(data)
        await axios.post('/api/users/getGroupOptionSingle', data)
        .then(res => {
            // console.log(res, '数据库添加单个群信息成功')
            let groupParams = {flag: 3, arr: [res.data]}
            commit(types.SET_GROUP_INFO, groupParams)
        })
        .catch(err => {
            console.log(err, '数据库添加单个群信息成功')
        })
      // }
    },
    // 用户登录就从数据库获取到标签的相关信息************
    async getLabelInfo({commit, state}) {
      let result = []
      // 将具体的群组信息存入vuex
      commit(types.SET_LABEL_INFO, result)
      console.log(state.labelInfo)
      },
    // 用户创建标签后添加一个标签信息
    async addLabelInfo({commit, state}, option) {
      commit(types.ADD_LABEL_INFO, option)
      console.log('用户创建标签后添加一个标签信息', state.labelInfo)
      // 将信息存进数据库*************
    },
    async sendFile({commit, state}, obj) {
      // console.log(obj)
      /**
       obj.type = singleChat from: obj.filePrefix.split('/')[0] to(cwf13): obj.filePrefix.split('/')[1]
       obj.type = headIcon self: obj.filePrefix.split('/')[0]
       */

      // 从后端获取token上传文件的凭证
      let result = await axios.get('/api/users/fileSend')
          .then(res => {
              console.log(res, '获取上传文件token成功')
              return Promise.resolve(res.data)
          })
          .catch(err => {
              console.log(err, '获取上传文件token失败')
      })
      // result-->token
      if (result) {
        // 七牛云的存储地区选择
        let config = {
          useCdnDomain: true,
          region: qiniu.region.z2
        }
        let putExtra = {
          // 资源名字
          fname: obj.name,
          // 自己定义的变量
          params: {filePrefix: obj.filePrefix},
          // 上传文件的类型，不设置限制
          mimeType: null
        }
        // 上传到七牛云的目录
        let key = obj.filePrefix + '/' + obj.name
        // let key = 'default/groupicon.jpg'
        // 上传文件
        let observable = qiniu.upload(obj.file, key, result, putExtra, config)
        // 上传文件的结果
        // eslint-disable-next-line
        let observer = {
          next(res) {
            console.log('正在上传文件', res)
          },
          error(err) {
            console.log('上传文件失败', err)
          },
          complete(res) {
            console.log('上传文件完成', res)
            if (obj.type === 'headIcon') {
              // console.log('修改头像', 'http://minichat.guozhengfeng.cn/cwf13/headIcon/timg1.jpg')
              let url = 'http://minichat.guozhengfeng.cn/' + key
              // let url = 'http://minichat.guozhengfeng.cn/cwf13/headIcon/timg1.jpg'
              // 修改vuex内容修改头像路径
              commit(types.RESET_HEAD_ICON, url)
              // 修改数据库的内容
              let data = {username: state.currentLoginUser.username, headicon: url}
              // let data = {username: 'cwf13', headicon: url}
              axios.post('/api/users/resetUserInfoHeadicon', data)
                .then(res => {
                    console.log(res, '请求成功')
                })
                .catch(err => {
                    console.log(err, '数据库修改头像请求失败')
              })
            }
          }
        }
        let subscription = observable.subscribe(observer) // 上传开始
        console.log(subscription)
      }
     /*
      if (obj.type === 'headIcon') {
        console.log('修改头像', 'http://minichat.guozhengfeng.cn/cwf13/headIcon/timg1.jpg')
        // let url = 'http://minichat.guozhengfeng.cn/' + key
        let url = 'http://minichat.guozhengfeng.cn/cwf13/headIcon/timg1.jpg'
        // 修改vuex内容修改头像路径
        commit(types.RESET_HEAD_ICON, url)
        // 修改数据库的内容
        // let data = {username: state.currentLoginUser.username, jid: jid}
        let data = {username: 'cwf13', headicon: url}
        await axios.post('/api/users/resetUserInfoHeadicon', data)
          .then(res => {
              console.log(res, '数据库删除好友信息成功')
          })
          .catch(err => {
              console.log(err, '数据库删除好友信息失败')
        })
      }
      */
    }
}
export default action
